/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.semi.fw;
import com.semi.util.FileLogger;
import java.io.IOException;  
  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
/**
 *
 * @author liaoyq
 */
public class UnCodeFilter implements Filter   {
    private String encoding;
    private FileLogger mLog = new FileLogger(UnCodeFilter.class.getName());
    private CodeCenter mChecker = new CodeCenter();
    public void init(FilterConfig filterConfig) throws ServletException {  
        mLog.info("fw "+mChecker.version()+", setup.......");
        encoding = filterConfig.getInitParameter("encoding"); 
        mChecker.setup("fw.xml");
    }
    public void destroy() {
        mLog.info("fw down.......");
        mChecker.shutdown();
    }    
    /** 
     * 判断Request ,Response 类型 
     * @param request 
     *            ServletRequest 
     * @param response 
     *            ServletResponse 
     * @throws ServletException  
     */  
    private boolean checkRequestResponse(ServletRequest request,  
            ServletResponse response) throws ServletException {  
        if (!(request instanceof HttpServletRequest)) {  
            return false;
  
        }  
        if (!(response instanceof HttpServletResponse)) {  
            return false;
        }  
        return true;
    }      
    public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException { 
        if( !checkRequestResponse(request,response) ){
            chain.doFilter(request, response);
            return;
        }
     
        //if(encoding != null)    request.setCharacterEncoding(encoding);
        if( !mChecker.validateCode( (HttpServletRequest) request,encoding))
                chain.doFilter(request, response);
    }       
}
